package org.fall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import crowd.entity.Admin;
import crowd.entity.AdminExample;
import org.fall.constant.CrowdConstant;
import org.fall.exception.LoginFailedException;
import org.fall.mapper.AdminMapper;
import org.fall.service.api.AdminService;
import org.fall.util.CrowdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author XZ
 * @create 2021-11-27 12:05
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    AdminMapper adminMapper;
    public void save(Admin admin) {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String creatTime = dateFormat.format(date);
        admin.setCreateTime(creatTime);

        String userPswd = admin.getUserPswd();
        userPswd = CrowdUtil.md5(userPswd);
        admin.setUserPswd(userPswd);

        adminMapper.insert(admin);
    }

    public List<Admin> getAll() {
        return adminMapper.selectByExample(new AdminExample());
    }

    public Admin getAdminByUsername(String userName, String password) {
        //1、根据登陆账号查询Admin对象
        // 创建AdminExample对象
        AdminExample adminExample = new AdminExample();
        //创建Criteria对象
        AdminExample.Criteria criteria = adminExample.createCriteria();
        //在Criteria对象中封装查询的条件
        criteria.andLoginAcctEqualTo(userName);
        // 调用AdminMapper的方法来查询
        List<Admin> admins = adminMapper.selectByExample(adminExample);
        if (admins == null || admins.size() == 0) {
            throw  new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
        if (admins.size() > 1) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
        }

        //2、判断Admin对象是否为空
        Admin admin = admins.get(0);
        if (admin == null) {
            //3、若admin对象为null则抛出异常
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        //4、若Admin对象不为null则将数据库密码从Admin对象中取出
        String userPswd = admin.getUserPswd();
        //5、将表单提交的明文密码就进行加密
        String userPassword = CrowdUtil.md5(password);
        //6、对密码进行比较
        if (!Objects.equals(userPassword, userPswd)) {
            //7、如果比较结果不一致则抛出异常
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
        //8、如果一致则返回admin对象
        return admin;

    }

    @Override
    public PageInfo<Admin> getPageInfo(String keyword, Integer pageNum, Integer pageSize) {
        // 利用PageHelper的静态方法开启分页
        PageHelper.startPage(pageNum, pageSize);

        // 调用Mapper接口的对应方法
        List<Admin> admins = adminMapper.selectAdminByKeyword(keyword);

        // 为了方便页面的使用，把Admin的List封装成PageInfo（放别得到页码等数据）
        PageInfo<Admin> pageInfo = new PageInfo<>(admins);

        // 返回得到的pageInfo对象
        return pageInfo;
    }

    @Override
    public void removeById(Integer adminId) {
        adminMapper.deleteByPrimaryKey(adminId);
    }

    @Override
    public Admin queryAdmin(Integer adminId) {
        Admin admin = adminMapper.selectByPrimaryKey(adminId);
        return admin;
    }

    @Override
    public void updateAdmin(Admin admin) {
        try {
            adminMapper.updateByPrimaryKeySelective(admin);
        } catch (Exception e) {
            e.printStackTrace();
            // 这里出现异常的话一般就是DuplicateKeyException（因为插入的loginAcct已存在而触发）
            if(e instanceof DuplicateKeyException){
                // 如果确实是DuplicateKeyException，此时抛出一个自定义的异常
                throw new LoginFailedException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
            }
        }
    }
//clearOldRelationship
    //saveAdminRoleRelationship
    @Override
    public void saveAdminRoleRelationship(Integer adminId, List<Integer> roleIdList) {
        // 先清除旧的对应inner_admin_role表中对应admin_id的数据
        adminMapper.clearOldRelationship(adminId);
        // 如果roleIdList非空，则将该list保存到数据库表中，且admin_id=adminId
        if (roleIdList != null && roleIdList.size() > 0) {
            adminMapper.saveAdminRoleRelationship(adminId, roleIdList);
        }
        // roleIdList为空，则清空后不做操作

    }
}
